package com.lv.service.ui

import android.Manifest
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.widget.RelativeLayout
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.lv.common.base.BaseActivity
import com.lv.common.ktx.LoadSrc
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.DensityUtil
import com.lv.common.utils.PermissionXUtils
import com.lv.common.utils.PermissionXUtilsCallback
import com.lv.common.utils.SaveImageUtils
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.TimeUtil
import com.lv.common.utils.YgxUtilsKt
import com.lv.common.utils.showToast
import com.lv.service.R
import com.lv.service.bean.CompanyCertificateBean
import com.lv.service.bean.CompanyCertificateChildBean
import com.lv.service.databinding.ActivityShowBitmapScaleBinding

/**
 * 作者： ygx
 * 创建日期：2023/3/28 5:51 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：bitmap图片点击放大页面 下载
 */
@Route(path = ARoutUtils.ShowBitmapScaleActivity)
class ShowBitmapScaleActivity : BaseActivity<ActivityShowBitmapScaleBinding>(),
    View.OnClickListener {

    @Autowired(name = "name")
    @JvmField
    var mName: String = ""

    @Autowired(name = "item")
    @JvmField
    var mCard: CompanyCertificateBean? = null
    private var mBitmap: Bitmap? = null
    private var mScrennK = 360 / (375.0f * 3) //比例系数


    override fun getLayoutRes() = R.layout.activity_show_bitmap_scale
    override fun initView() {
        super.initView()
        initStatusBar(this, true, false)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@ShowBitmapScaleActivity, titleBar)
            titleBar.setTitle("喜报生成")
            titleBar.setLeftIcon(com.lv.common.R.drawable.icon_back_white)
            titleBar.setTitleColor(Color.parseColor("#ffffff"))
            titleBar.onClickBackIcon { finish() }
            tvCancel.setOnClickListener(this@ShowBitmapScaleActivity)
            tvSave.setOnClickListener(this@ShowBitmapScaleActivity)
        }
    }


    override fun initConfig() {
        super.initConfig()
        when (mCard?.styleIndex) {
//            0 -> mName = "恭喜：${mName}成为速易甬"
            2 -> mBinding.tvCpname.gravity = Gravity.CENTER_VERTICAL
//            1 -> mName = "$mName\n成为速易甬平台"
//            7 -> mName = "恭喜：${mName}成为速易甬"
        }
        mBinding.tvCpname.text = mName
        mScrennK = (mCard?.bgW ?: 0) / 360.0f
        val bgH = (mCard?.bgH ?: 0) / mScrennK
        val layoutParams = mBinding.ivImage.layoutParams as RelativeLayout.LayoutParams
        layoutParams.height = DensityUtil.dip2px(this, bgH)
        mBinding.ivImage.layoutParams = layoutParams
        val cpNameRect = mCard?.cpNameRect
        val nameRect = mCard?.nameRect
        val timeRect = mCard?.timeRect
        initViewStyle(cpNameRect, mBinding.tvCpname)
        initViewStyle(nameRect, mBinding.tvName)
        initViewStyle(timeRect, mBinding.tvTime)
        if (mCard?.styleIndex == 1) {
            mBinding.tvCpname.maxLines = (cpNameRect?.numberOfLine ?: 1) + 1
        }
        mBinding.tvName.gravity = Gravity.END
        mBinding.tvTime.gravity = Gravity.END
        val time = TimeUtil.getDateTimeString(System.currentTimeMillis(), "yyyy年MM月dd日")
        mBinding.tvTime.text = time
        val bg = mCard?.bg
        val options = RequestOptions()
            .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
            .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
            .format(DecodeFormat.PREFER_RGB_565)
        Glide.with(this).load(bg).apply(options).addListener(object : RequestListener<Drawable> {
            override fun onLoadFailed(
                e: GlideException?,
                model: Any?,
                target: Target<Drawable>?,
                isFirstResource: Boolean
            ): Boolean {
                // 处理加载失败的情况
                return false
            }

            override fun onResourceReady(
                resource: Drawable?,
                model: Any?,
                target: Target<Drawable>?,
                dataSource: DataSource?,
                isFirstResource: Boolean
            ): Boolean {
                // 图片加载完成后的操作
//                showToast("图片加载完成后的操作")
                mBinding.ivImage.post {
                    mBitmap = SaveImageUtils.getViewGroupBitmapNoBg(mBinding.clContainerCard)
                    mBinding.ivPhoto.LoadSrc(mBitmap)
                }
                return false
            }
        }).into(mBinding.ivImage)
    }

    private fun initViewStyle(rect: CompanyCertificateChildBean?, textView: TextView) {
        val x = (rect?.x ?: 0) / mScrennK
        val h = (rect?.h ?: 0) / mScrennK
        val y = (rect?.y ?: 0) / mScrennK
        val w = (rect?.w ?: 0) / mScrennK
        val paramsCpName = textView.layoutParams as RelativeLayout.LayoutParams
        paramsCpName.topMargin = DensityUtil.dip2px(this, y)
        paramsCpName.leftMargin = DensityUtil.dip2px(this, x)
        paramsCpName.height = DensityUtil.dip2px(this, h)
        paramsCpName.width = DensityUtil.dip2px(this, w)
        textView.setTextColor(YgxUtilsKt.getColorForString(rect?.txtColor))
        textView.layoutParams = paramsCpName
//        textView.setBackgroundResource(com.lv.common.R.drawable.bg_line_0084ff_2)
        val fontSize = ((rect?.maxFont ?: 16) / mScrennK).toInt()
        textView.setAutoSizeTextTypeUniformWithConfiguration(
            1, fontSize, 1,
            TypedValue.COMPLEX_UNIT_SP
        )
        textView.maxLines = rect?.numberOfLine ?: 1
    }


    /**
     * 下载当前图片到SD卡
     */
    private fun downloadCurrentImg() {
        runOnUiThread {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                SaveImageUtils.saveImageToGallery2(
                    this@ShowBitmapScaleActivity, mBitmap,
                ) {
                    mBinding.tvSave.isEnabled = true
                    showToast("图片保存成功,请到相册查找")
                }
            } else {
                SaveImageUtils.saveImageToPhotos(
                    this@ShowBitmapScaleActivity, mBitmap,
                ) {
                    mBinding.tvSave.isEnabled = true
                    showToast("图片保存成功,请到相册查找")
                }
            }
        }
    }

    override fun initData() {
        super.initData()

    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.tv_save -> {
                mBinding.tvSave.isEnabled = false
                checkAndDownload()
            }

            R.id.tv_cancel -> finish()
        }
    }

    private fun checkAndDownload() {
        val permissions = mutableListOf<String>()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions.add(Manifest.permission.READ_MEDIA_IMAGES)
        } else {
            permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE)
        }
        PermissionXUtils.checkPermissBefore(
            this,
            permissions,
            "请授予存储权限，以便保存图片到手机相册",
            callback = object : PermissionXUtilsCallback {
                override fun permissionCallback(
                    allGranted: Boolean,
                    grantedList: List<String?>,
                    deniedList: List<String?>
                ) {
                    if (allGranted) {
                        // 下载当前图片
                        downloadCurrentImg()
                    } else {
                        mBinding.tvSave.isEnabled = true
                    }
                }

            })
    }

    override fun onDestroy() {
        super.onDestroy()
        mBitmap?.recycle()
    }

}